package com.shu.controller;

import com.shu.activemq.producer.IProducerService;
import com.shu.entity.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.jms.Destination;

@Controller
public class LoginController {
    private Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    private IProducerService producerService;
    @RequestMapping("/login")
    public String login(){
        return "login";
    }
    @RequestMapping(value = "/sublogin",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    public String sublogin(User user, Model model ){
        logger.info("==============helloworld=================="+user.getUserName());
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(),user.getPassword());

        try {
            subject.login(token);
            if(subject.isAuthenticated()){
                Destination destination = new Destination() {
                    @Override
                    public String toString() {
                        return "demo_queue";
                    }
                };
                producerService.sendMessage(destination,"登录成功");
                return "main";
            }
        } catch (AuthenticationException e){
            String msg = "用户或密码错误";
            String cc =e.getMessage();
            logger.info(cc);
            if (StringUtils.isNotEmpty(e.getMessage()))
            {
                msg = e.getMessage();
            }
            model.addAttribute("error",msg);
        }
        model.addAttribute("user",user);
        return "login";
    }
}
